<?php
/**
 * 城市model
 * User: cxm
 * Date: 2019/1/25 0025
 * Time: 14:28
 */

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class Region extends BaseModel
{
    use SoftDeletes;
    protected $dates = ['deleted_at']; //开启deleted_at
    protected $table = 'region';
    // 下级数量
    protected $appends = ['child_count'];

    /**
     * 计算下级数量
     */
    public function getChildCountAttribute() {
        if (!isset($this->attributes['id']) || empty($this->attributes['id'])) {
            return 0;
        }
        $city_id = $this->attributes['id'];
        $count = self::getChildCount($city_id);
        return $count;
    }
    /**
     * 获取下级总数
     * @param $city_id
     * @return mixed
     */
    public static function getChildCount($city_id){
        return self::where('parent_id',$city_id)->count();
    }

    /**
     * 通过名称获取ID
     * @param string $name 名称
     * @param int $le 级层
     * @param int $pid 上级ID
     * @return string
     */
    public static function getByNameId(string $name, int $le = 0, int $pid = 0)
    {
        $where[] = ['name', $name];
        if ($le) {
            $where[] = ['level', $le];
        }
        if ($pid) {
            $where[] = ['parent_id', $pid];
        }
        return self::where($where)->first() ?: '';
    }

    /**
     * 通过名称获取ID
     * @param string $name 名称
     * @param int $le 级层
     * @param int $pid 上级ID
     * @return string
     */
    public static function getByShortNameId(string $name, int $le = 0, int $pid = 0)
    {
        $where[] = ['short_name', $name];
        if ($le) {
            $where[] = ['level', $le];
        }
        if ($pid) {
            $where[] = ['parent_id', $pid];
        }
        return self::where($where)->value('id') ?: '';
    }

    /**
     * 通过ID获取名称
     * @param $id
     * @return string
     */
    public static function getByIdName($id)
    {
        return self::where('id', $id)->value('name') ?: '';
    }

    /**
     * 获取父级ID
     * @param $pid  父ID
     * @return mixed
     */
    public static function findFatherId($pid){
        return self::where('id',$pid)->value('parent_id');
    }

    /**
     * 查询列表
     * @param $where 查询条件
     * @param $orderBy 排序方式
     * @param $page 页码
     * @param $limit 每页显示条数
     * @return mixed
     */
    public static function getData($where,$orderBy,$page,$limit){
        DB::enableQueryLog();
        $result = self::where($where);
        if ($orderBy) {
            foreach ($orderBy as $item) {
                $result->orderBy($item[0],$item[1]);
            }
        }else{
            $result->orderBy('created_at','desc');
        }
        $count = $result->count();
        $data = $result->skip(($page - 1) * $limit)->take($limit)->get()->toArray();
        return ['total'=>$count,'data'=>$data];
    }

    /**
     * 获取地址
     * @param $province 省
     * @param $city 市
     * @param $district 区
     * @return mixed
     */
    public static function getName($province,$city,$district){
        $string = '';
        if ($province) {
            $string .= ' '. self::getNameById($province);
        }
        if ($city) {
            $string .= ' '. self::getNameById($city);
        }
        if ($district) {
            $string .= ' '. self::getNameById($district);
        }
        return $string;
    }

    /**
     * 根据地址ID获取名称
     * @param $id
     * @param string $field 字段
     * @return mixed
     */
    public static function getNameById($id,$field='name'){
        return self::where('id',$id)->value($field);
    }

    /**
     * 功能:导出区域信息到 JSON 文件
     * @return bool
     */
    static public function exportAll2Json()
    {
        $areas = self::select(['id', 'parent_id', 'name', 'level'])
            ->where('level','<=',3)
            ->orderBy('level', 'DESC')
            ->orderBy('id')
            ->get()
            ->toArray();
        $area_id_2_index = array_flip(array_column($areas, 'id'));

        $temp = [];

        foreach ($areas as &$area) {
            if ($area['parent_id'] == 0){
                array_push($temp, $area);
                continue;
            }

            $parent_index= $area_id_2_index[$area['parent_id']]; //父级所在数组索引
            if(!array_key_exists('sub_areas', $areas[$parent_index])){
                $areas[$parent_index]['sub_areas'] = [];
            }

            array_push($areas[$parent_index]['sub_areas'], $area);
        }

        //如果不存目录则创建
        if(!file_exists('./area_json')){
            mkdir('./area_json');
//            chmod('./area_json', '0777');
        }

        //独占锁更新文件
        file_put_contents('./area_json/all.json', json_encode($temp));

        //独占锁更新 json 更新日期
        file_put_contents('./area_json/all.lock', json_encode(['time'=>time()]));
        unset($areas);
        unset($temp);
        return true;
    }

    /**
     * 功能:导出市信息到 JSON 文件
     * @return bool
     */
    static public function exportProvinceAndHotJson(){
        $list = Region::where([['level', 2], ['status', 1]])->get(['id', 'name', 'short_name', 'initials','level'])->toArray();
        $data['list'] = groupByInitials($list, 'initials');
        // 热门城市
        $hot_city = Region::where([ ['status', 1],['is_hot',1]])->get(['id', 'name', 'short_name', 'initials','level'])->toArray();
        $data['hot_city'] = $hot_city;
        //如果不存目录则创建
        if(!file_exists('./area_json')){
            mkdir('./area_json');
//            chmod('./area_json', '0777');
        }

        //独占锁更新文件
        file_put_contents('./area_json/province.json', json_encode($data));

        //独占锁更新 json 更新日期
        file_put_contents('./area_json/province.lock', json_encode(['time'=>time()]));
        unset($areas);
        unset($temp);
        return true;
    }

    /**
     * 获取所有数据
     */
    public static function dataGroup(){
        $data = self::select(['id as value', 'parent_id', 'name as label', 'level'])
            ->orderBy('level', 'DESC')
            ->orderBy('id')
            ->get()
            ->map(function ($append) {
                return $append->setAppends([]);
            })
            ->toArray();
        $area_id_2_index = array_flip(array_column($data, 'value'));

        $temp = [];

        foreach ($data as &$area) {
            if ($area['parent_id'] == 0){
                array_push($temp, $area);
                continue;
            }

            $parent_index= $area_id_2_index[$area['parent_id']]; //父级所在数组索引
            if(!array_key_exists('children', $data[$parent_index])){
                $data[$parent_index]['children'] = [];
            }

            array_push($data[$parent_index]['children'], $area);
        }
        return $temp;
    }

    /**
     * 地区联动获取
     * @param int $pid
     * @return mixed
     */
    public static function getByPid(int $pid = 0)
    {
        $list = self::where([['parent_id', $pid], ['status', 1]])
            ->get(['id', 'name', 'short_name'])
            ->toArray();
        return $list;
    }

}